import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class LoginController {
    public static Map<String, String> userDatabase = new HashMap<>();
    public static Map<String, String> userRoles = new HashMap<>();
    private static final String USER_DATA_FILE = "user_data.txt";
    private static final String USER_ROLE_FILE = "user_role.txt";

    public static void showLoginFrame(JFrame frame) {
        frame.getContentPane().removeAll();
        frame.getContentPane().revalidate();
        frame.getContentPane().repaint();


        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(0, 2));

        JLabel usernameLabel = new JLabel("用户名:");
        JTextField usernameField = new JTextField();
        JLabel passwordLabel = new JLabel("密码:");
        JPasswordField passwordField = new JPasswordField();
        JButton loginButton = new JButton("登录");
        JButton registerButton = new JButton("注册");
        JButton exitButton = new JButton("退出系统");

        panel.add(usernameLabel);
        panel.add(usernameField);
        panel.add(passwordLabel);
        panel.add(passwordField);
        panel.add(loginButton);
        panel.add(registerButton);
        panel.add(exitButton);

        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = usernameField.getText();
                String password = new String(passwordField.getPassword());

                String userRole = authenticate(username, password);
                if (userRole != null) {
                    JOptionPane.showMessageDialog(frame, "登录成功!");
                    MenuController.showMainMenu(frame, username, userRole);
                } else {
                    JOptionPane.showMessageDialog(frame, "密码错误!");
                }
            }
        });

        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                registerUser(frame);
            }
        });

        exitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.dispose();
            }
        });

        frame.getContentPane().add(panel);
        frame.revalidate();
        frame.repaint();
    }

    private static String authenticate(String username, String password) {
        // 这里可以添加真实的认证逻辑，比如查询数据库
        if (userDatabase.containsKey(username) && userDatabase.get(username).equals(password)) {
            return userRoles.getOrDefault(username, "普通用户");
        }
        return null;
    }

    private static void registerUser(JFrame frame) {
        JFrame registerFrame = new JFrame("注册");
        registerFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        registerFrame.setSize(300, 200);
        registerFrame.setLocationRelativeTo(null);
        registerFrame.setVisible(true);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(0, 2));

        JLabel usernameLabel = new JLabel("用户名:");
        JTextField usernameField = new JTextField();
        JLabel passwordLabel = new JLabel("密码:");
        JPasswordField passwordField = new JPasswordField();
        JButton registerButton = new JButton("注册");

        panel.add(usernameLabel);
        panel.add(usernameField);
        panel.add(passwordLabel);
        panel.add(passwordField);
        panel.add(registerButton);

        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = usernameField.getText();
                String password = new String(passwordField.getPassword());

                if (userDatabase.containsKey(username)) {
                    JOptionPane.showMessageDialog(registerFrame, "用户名已存在，请选择其他用户名.");
                } else {
                    userDatabase.put(username, password);
                    userRoles.put(username, "普通用户");
                    JOptionPane.showMessageDialog(registerFrame, "注册成功!");
                    saveUserData();
                    saveUserRoles();
                    registerFrame.dispose();
                }
            }
        });

        registerFrame.getContentPane().add(panel);
        registerFrame.revalidate();
        registerFrame.repaint();
    }

    public static void loadUserData() {
        try (BufferedReader br = new BufferedReader(new FileReader(USER_DATA_FILE))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(":", 2);
                if (parts.length == 2) {
                    userDatabase.put(parts[0], parts[1]);
                }
            }
        } catch (IOException e) {
            // 文件不存在或其他IO错误，忽略
        }
    }

    private static void saveUserData() {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(USER_DATA_FILE))) {
            for (Map.Entry<String, String> entry : userDatabase.entrySet()) {
                bw.write(entry.getKey() + ":" + entry.getValue());
                bw.newLine();
            }
        } catch (IOException e) {
            System.out.println("保存用户数据时发生错误: " + e.getMessage());
        }
    }

    public static void loadUserRoles() {
        try (BufferedReader br = new BufferedReader(new FileReader(USER_ROLE_FILE))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(":", 2);
                if (parts.length == 2) {
                    userRoles.put(parts[0], parts[1]);
                }
            }
        } catch (IOException e) {
            // 文件不存在或其他IO错误，忽略
        }
    }

    private static void saveUserRoles() {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(USER_ROLE_FILE))) {
            for (Map.Entry<String, String> entry : userRoles.entrySet()) {
                bw.write(entry.getKey() + ":" + entry.getValue());
                bw.newLine();
            }
        } catch (IOException e) {
            System.out.println("保存用户角色数据时发生错误: " + e.getMessage());
        }
    }

    // 用户管理逻辑
    public static void showUserManagementFrame(JFrame frame, String loggedInUser, String userRole) {
        frame.getContentPane().removeAll();
        frame.getContentPane().revalidate();
        frame.getContentPane().repaint();

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(0, 1));

        JTextArea userTextArea = new JTextArea();
        userTextArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(userTextArea);

        JButton addUserButton = new JButton("添加用户");
        JButton editUserButton = new JButton("编辑用户");
        JButton backButton = new JButton("返回主菜单");

        // 自动显示所有用户
        userTextArea.append("用户列表:\n");
        for (String username : userDatabase.keySet()) {
            userTextArea.append(username + " - " + userRoles.get(username) + "\n");
        }

        panel.add(scrollPane);
        panel.add(addUserButton);
        panel.add(editUserButton);
        panel.add(backButton);

        addUserButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFrame addUserFrame = new JFrame("添加用户");
                addUserFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                addUserFrame.setSize(300, 200);
                addUserFrame.setLocationRelativeTo(null);
                addUserFrame.setVisible(true);

                JPanel addUserPanel = new JPanel();
                addUserPanel.setLayout(new GridLayout(0, 2));

                JLabel newUsernameLabel = new JLabel("新用户名:");
                JTextField newUsernameField = new JTextField();
                JLabel newPasswordLabel = new JLabel("新密码:");
                JPasswordField newPasswordField = new JPasswordField();
                JLabel newRoleLabel = new JLabel("用户角色 (创建者/管理者/普通用户):");
                JTextField newRoleField = new JTextField();
                JButton addUserConfirmButton = new JButton("添加");

                addUserPanel.add(newUsernameLabel);
                addUserPanel.add(newUsernameField);
                addUserPanel.add(newPasswordLabel);
                addUserPanel.add(newPasswordField);
                addUserPanel.add(newRoleLabel);
                addUserPanel.add(newRoleField);
                addUserPanel.add(addUserConfirmButton);

                addUserConfirmButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        String newUsername = newUsernameField.getText();
                        String newPassword = new String(newPasswordField.getPassword());
                        String newRole = newRoleField.getText();

                        if (userDatabase.containsKey(newUsername)) {
                            JOptionPane.showMessageDialog(addUserFrame, "用户名已存在，请选择其他用户名.");
                        } else {
                            userDatabase.put(newUsername, newPassword);
                            userRoles.put(newUsername, newRole);
                            JOptionPane.showMessageDialog(addUserFrame, "用户添加成功!");
                            saveUserData();
                            saveUserRoles();
                            addUserFrame.dispose();
                            showUserManagementFrame(frame, loggedInUser, userRole);
                        }
                    }
                });

                addUserFrame.getContentPane().add(addUserPanel);
                addUserFrame.revalidate();
                addUserFrame.repaint();
            }
        });

        editUserButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFrame editUserFrame = new JFrame("编辑用户");
                editUserFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                editUserFrame.setSize(300, 200);
                editUserFrame.setLocationRelativeTo(null);
                editUserFrame.setVisible(true);

                JPanel editUserPanel = new JPanel();
                editUserPanel.setLayout(new GridLayout(0, 2));

                JLabel editUsernameLabel = new JLabel("要编辑的用户名:");
                JTextField editUsernameField = new JTextField();
                JLabel newRoleLabel = new JLabel("新的用户角色:");
                JComboBox<String> newRoleComboBox = new JComboBox<>(new String[]{"普通用户", "管理者"});
                JButton editUserConfirmButton = new JButton("编辑");

                // 如果当前用户是创建者，允许选择创建者
                if ("创建者".equals(userRole)) {
                    newRoleComboBox.addItem("创建者");
                }

                editUserPanel.add(editUsernameLabel);
                editUserPanel.add(editUsernameField);
                editUserPanel.add(newRoleLabel);
                editUserPanel.add(newRoleComboBox);
                editUserPanel.add(editUserConfirmButton);

                editUserConfirmButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        String editUsername = editUsernameField.getText();
                        String newRole = (String) newRoleComboBox.getSelectedItem();

                        if (userDatabase.containsKey(editUsername)) {
                            if ("创建者".equals(editUsername) && !"创建者".equals(userRole)) {
                                JOptionPane.showMessageDialog(editUserFrame, "无法更改创建者信息.");
                            } else {
                                userRoles.put(editUsername, newRole);
                                JOptionPane.showMessageDialog(editUserFrame, "用户权限更改成功!");
                                saveUserRoles();
                                editUserFrame.dispose();
                                showUserManagementFrame(frame, loggedInUser, userRole);
                            }
                        } else {
                            JOptionPane.showMessageDialog(editUserFrame, "用户不存在.");
                        }
                    }
                });

                editUserFrame.getContentPane().add(editUserPanel);
                editUserFrame.revalidate();
                editUserFrame.repaint();
            }
        });

        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MenuController.showMainMenu(frame, loggedInUser, userRole);
            }
        });

        frame.getContentPane().add(panel);
        frame.revalidate();
        frame.repaint();
    }
}